<?php

namespace app\admin\controller\activity;

use app\common\controller\Backend;
use think\Db;

/**
 * 拼团时间段管理
 *
 * @icon fa fa-group
 */
class GroupDetail extends Backend
{
    
    /**
     * Group模型对象
     * @var \app\admin\model\activity\Group
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\activity\Group;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看拼团时间段详情
     *@$group_info  拼团时间段表数据查找
     *@$group_all_info   拼团商品表, 拼团限制表, 拼团价格区域表, 商品表联合查询查找
     */
    public function index()
    {
        $id = input("ids");

        $group_info = Db::name("group")->where("id", $id)->find();

        $group_all_info = Db::name('group g')
                            ->where("g.id", $id)
                            ->join('group_goods gg', 'g.id = gg.group_id')
                            ->join('shopro_goods sg', 'gg.goods_id = sg.id')
                            ->field("sg.title, sg.image, sg.original_price, sg.id as sgid, gg.start_time, gg.update_time, gg.id")
                            ->select();
        $this->assign("group_info", $group_info);
        $this->assign("group_all_info", $group_all_info);
        return $this->fetch();
    }

    /**
     * 查看该时间段拼团商品和展示所有商品
     *@$all_goods   所有的商品
     *@$have_goods  该时间段拼团商品
     */
    public function details()
    {
        $group_id = input("group_id");
        $all_goods = Db::name('shopro_goods')->select();
        $have_goods = Db::table("fa_group_goods")->where("group_id", $group_id)->column("goods_id");
        // var_dump($have_goods);die;
        if(empty($have_goods)){
            $have_goods = [];
        }
        $this->assign("group_id", $group_id);
        $this->assign("all_goods", $all_goods);
        $this->assign("have_goods", $have_goods);
        return $this->fetch();
    }

    /**
     * 对拼团商品表进行重新绑定,解绑
     */
    public function choice()
    {
        $group_id = input("group_id");
        $choice = input("choice");
        $old_result = Db::name("group_goods")->where("group_id", $group_id)->column('goods_id');
        if(empty($old_result)){
            $old_result = [];
        }
        $new_result = explode(',', $choice);
        $intersection = array_intersect($old_result, $new_result);
        $del_info = array_diff($old_result, $intersection);
        $ins_info = array_diff($new_result, $intersection);
        $time = time();
        Db::startTrans();
        try{
            if(!empty($del_info)){
                $del_id_array = Db::name("group_goods")->where('group_id', $group_id)->whereIn('goods_id', $del_info)->column("id");
                // return $del_id_array;
                //删除操作
                Db::name("group_goods")->whereIn("id", $del_id_array)->delete();
                $group_goods_sku_id = Db::name("group_goods_sku")->whereIn("gg_id", $del_id_array)->column("id");
                Db::name("group_goods_sku")->whereIn("gg_id", $del_id_array)->delete();
                Db::name("group_area")->whereIn("ggs_id", $group_goods_sku_id)->delete();
                Db::name("group_astrict")->whereIn("ggs_id", $group_goods_sku_id)->delete();

            }
            if(!empty($ins_info)){
                foreach($ins_info as $v){
                    $data = [
                        'goods_id' => $v,
                        'group_id' => $group_id,
                        'start_time' => $time,
                        'update_time' => $time
                    ];
                    $insert_id = Db::name("group_goods")->insert($data);
                    // $insert_id = Db::name("group_goods")->insertGetId($data);
                    // $sgkp_id = Db::name("shopro_goods_sku_price")->where("goods_id", $v)->column("id");
                    // foreach($sgkp_id as $x){
                    //     $info = [
                    //         'gg_id' => $insert_id,
                    //         'sku_price_id' => $x
                    //     ];
                    //     Db::name("group_goods_sku")->insert($info);
                    // }
                }
            }
            DB::commit();
            $end_info = true;
        } catch (\Exception $e) {
            DB::rollBack();
            $end_info = false;
        }
        if($end_info == true){
            $arr = [
               'state'     => 1,
               'message'  => "更新成功！"
            ];
        }else{
            $arr = [
               'state'     => 2,
               'message'  => "更新失败！"
            ];
        }
        return json($arr);
    }

    public function delete(){
        $id = input('id');
        Db::startTrans();
        try{
            Db::name('group_goods')->delete($id);
            $group_goods_sku_id = Db::name("group_goods_sku")->where("gg_id", $id)->column("id");
            Db::name("group_goods_sku")->where("gg_id", $id)->delete();
            Db::name("group_area")->whereIn("ggs_id", $group_goods_sku_id)->delete();
            Db::name("group_astrict")->whereIn("ggs_id", $group_goods_sku_id)->delete();

            DB::commit();
            $end_info = true;
        } catch (\Exception $e) {
            DB::rollBack();
            $end_info = false;
        }
        if($end_info){
            $arr = [
               'state'     => 1,
               'message'  => "成功！"
            ];
        }else{
            $arr = [
               'state'     => 0,
               'message'  => "失败！"
            ];
        }
        return json($arr);
    }

    public function update()
    {
        $info = json_decode(input("info"), true);
        $gg_id = input("gg_id");
        foreach ($info as $key=>$val){
            if(empty($val['ggs_id'])){
                $insert_id = Db::name('group_goods_sku')->insertGetId(['gg_id' => $gg_id, 'sku_price_id' => $val['sgkp_id']]);
                $info[$key]['ggs_id'] = $insert_id;
                unset($info[$key]['sgkp_id']);
                $result = Db::name('group_astrict')->insert($info[$key]);
            }else{
                unset($info[$key]['sgkp_id']);
                $result = Db::name("group_astrict")->where('ggs_id', $val['ggs_id'])->update($info[$key]);
            }
        }
        $arr = [
               'state'     => 1,
               'message'  => "成功！"
            ];
        return json($arr);
    }

    /*
      *加载人员区间管理界面
    */
    public function other()
    {
        $ggs_id = input("ggs_id");
        $info = Db::name("group_area")->where("ggs_id", $ggs_id)->select();
        // var_dump($info);die;
        $this->assign("info", $info);
        $this->assign("ggs_id", $ggs_id);

        return $this->fetch();
    }

    public function update_area()
    {
        $ggs_id = input("ggs_id");
        $info = json_decode(input("info"), true);
        // return $info;
        Db::startTrans();
        try{
            $find_info = Db::name("group_area")->where("ggs_id", $ggs_id)->find();
            if(!empty($find_info)){
                Db::name("group_area")->where("ggs_id", $ggs_id)->delete();
            }
            foreach($info as $k=>$v){
                Db::name("group_area")->insert(['ggs_id' => $ggs_id, 'max_person_value' => $v['max_person_value'], 'price' => $v['price']]);
            }
            // DB::commit();
            $end_info = true;
        } catch (\Exception $e) {
            DB::rollBack();
            $end_info = false;
        }
        if($end_info == true){
            $arr = [
               'state'     => 1,
               'message'  => "更新成功！"
            ];
        }else{
            $arr = [
               'state'     => 2,
               'message'  => "更新失败！"
            ];
        }
        return json($arr);
    }

    /**** 加载选择规格界面 ****/
    public function select_sku()
    {   
        $gg_id = input("gg_id");
        $all_sku = Db::name("group_goods gg")
                    ->where("gg.id", $gg_id)
                    ->join("shopro_goods_sku_price sgkp", 'sgkp.goods_id = gg.goods_id')
                    ->join("group_goods_sku ggs", 'ggs.gg_id = gg.id and ggs.sku_price_id = sgkp.id', 'left')
                    ->join("group_astrict gat", 'gat.ggs_id = ggs.id', 'left')
                    ->field("sgkp.goods_sku_text, sgkp.price as old_price, sgkp.stock, sgkp.id as sgkp_id,gat.*, ggs.id as ggs_id")
                    ->select();
        foreach($all_sku as $k=>$v){
            if(empty($v['ggs_id'])){
                $assigned_store = Db::name('group_goods_sku ggs')
                                ->where('ggs.sku_price_id', $v['sgkp_id'])
                                ->join("group_astrict gat", "gat.ggs_id = ggs.id")
                                ->sum('store');
            }else{
                $assigned_store = Db::name('group_goods_sku ggs')
                                ->where('ggs.sku_price_id', $v['sgkp_id'])
                                ->where("ggs.id", "<>", $v['ggs_id'])
                                ->join("group_astrict gat", "gat.ggs_id = ggs.id")
                                ->sum('store');
            }
            $all_sku[$k]['assigned_store'] = $assigned_store;
        }
        $this->assign("all_sku", $all_sku);
        $this->assign("gg_id", $gg_id);
 
        return $this->fetch();
    }

    /****  修改拼团商品规格  ****/
    public function checked_sku()
    {
        $gg_id = input('gg_id');
        $checked_sku = input('checked_sku');
        $find_info = Db::name("group_goods_sku")->where("gg_id", $gg_id)->find();
        if($find_info){
            Db::name("group_goods_sku")->where("gg_id", $gg_id)->delete();
            $result = Db::name("group_goods_sku")->insert(['gg_id'=>$gg_id, 'sku_ids'=>$checked_sku]);
        }else{
            $result = Db::name("group_goods_sku")->insert(['gg_id'=>$gg_id, 'sku_ids'=>$checked_sku]);
        }
        if($result){
            $arr = [
               'state'     => 1,
               'message'  => "成功！"
            ];
        }else{
            $arr = [
               'state'     => 2,
               'message'  => "失败！"
            ];
        }
        return json($arr);
    }
}
